<template>
  <view class="urgent-order-container">
    <status-bar bgColor="#0088ff"></status-bar>
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <image src="/static/images/icon/backward_flat.png" class="back-icon-img"></image>
      </view>
      <view class="nav-title">加急订单</view>
    </view>

    <!-- 订单列表 -->
    <scroll-view scroll-y class="order-list">
      <block v-for="(order, index) in orderList" :key="index">
        <view class="order-item">
          <!-- 预约时间 -->
          <view class="appointment-time" v-if="order.appointmentTime">
            <text>预约时间：</text>
            <text class="time-value">{{ order.appointmentTime }}</text>
          </view>

          <!-- 订单编号和标签 -->
          <view class="order-header">
            <view class="order-no-container">
              <text class="order-no">订单编号：{{ order.orderNo }}</text>
              <view v-if="order.tag" class="order-tag urgent-tag">
                <text class="tag-icon">!</text>
                {{ order.tag }}
              </view>
            </view>
          </view>

          <!-- 客户信息和服务类型 -->
          <view class="customer-info">
            <view class="customer-left">
              <view class="location-icon">
                <image src="/static/images/icon/location.png" class="icon-img"></image>
              </view>
              <view class="customer-details">
                <view class="customer-name">{{ order.customerName }}</view>
                <view class="service-type-tag" :class="getServiceTypeClass(order.orderType)">
                  {{ order.orderType == '1' ? '窗帘测量' : '窗帘安装' }}
                </view>
              </view>
            </view>
            <view class="service-status">
              <text>{{ getOrderStatusText(order.orderStatus) }}</text>
              <text class="price">￥{{ order.price }}</text>
            </view>
          </view>

          <!-- 地址 -->
          <view class="order-address">
            <text class="address-text">{{ order.address }}</text>
          </view>

          <!-- 查看详情按钮 -->
          <view class="order-footer">
            <button class="detail-btn" @click="viewOrderDetail(order)">查看详情</button>
          </view>
        </view>
      </block>

      <!-- 加载中提示 -->
      <view class="loading-tip" v-if="loading">
        <uni-load-more
          status="loading"
          :contentText="{ contentdown: '加载中...', contentrefresh: '加载中...', contentnomore: '没有更多数据了' }"
        ></uni-load-more>
      </view>

      <!-- 无数据提示 -->
      <view class="empty-tip" v-if="!loading && noData">
        <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
        <text>暂无加急订单</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { ordeList } from '@/api/app/master/order.js'
import uniLoadMore from '@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue'

export default {
  components: {
    uniLoadMore
  },
  data() {
    return {
      orderList: [],
      loading: false,
      noData: false,
      pageNum: 1,
      pageSize: 100,
      total: 0
    }
  },
  onLoad() {
    this.loadUrgentOrders()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.pageNum = 1
    this.loadUrgentOrders().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.orderList.length < this.total) {
      this.pageNum++
      this.loadUrgentOrders()
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },

    // 获取服务类型样式类
    getServiceTypeClass(type) {
      if (type == '1') {
        return 'measure-tag'
      } else if (type == '2') {
        return 'install-tag'
      }
      return ''
    },

    // 获取订单状态文本
    getOrderStatusText(status) {
      const statusMap = {
        '1': '待派单',
        '2': '待预约',
        '3': '待服务',
        '4': '待验收',
        '5': '已完成',
        '9': '已售后',
        '99': '异常订单'
      }
      return statusMap[status] || '异常订单'
    },

    // 查看订单详情
    viewOrderDetail(item) {
      const status = this.getOrderStatusText(item.orderStatus)
      if (status === '待预约' || status === '异常订单') {
        uni.navigateTo({
          url: '/pages/order/order-appointment?id=' + item.id
        })
      } else if (status === '待服务' || status === '待验收' || status === '已完成' || status === '已售后') {
        uni.navigateTo({
          url: '/pages/order/order-detail?id=' + item.id
        })
      } else {

        uni.showToast({
          title: '查看订单: ' + item.id,
          icon: 'none'
        })


      }
    },

    // 姓名脱敏处理
    maskName(name) {
      if (!name) return ''
      if (name.length === 1) return name
      if (name.length === 2) return name.substring(0, 1) + '*'
      return name.substring(0, 1) + '*'.repeat(name.length - 2) + name.substring(name.length - 1)
    },

    // 加载加急订单数据
    loadUrgentOrders() {
      this.loading = true
      this.noData = false

      // 构建请求参数（筛选加急）
      const params = {
        urgent: 1,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }

      return ordeList(params)
        .then((res) => {
          if (res.code === 200) {
            const orders = res.rows || []
            this.total = res.total || 0

            if (this.pageNum === 1) {
              this.orderList = []
            }

            if (orders.length === 0 && this.pageNum === 1) {
              this.noData = true
            }

            // 过滤orders列表里边的数据，满足条件：orderStatus ！= 5 并且 orderStatus != 9
            for (let i = 0; i < orders.length; i++) {
              const item = orders[i]
              if (item.orderStatus === '5' || item.orderStatus === '9') {
                orders.splice(i, 1)
                i--
              }
            } // end of for



            const processedOrders = orders.map((item) => {
              // 格式化预约时间为 yyyy-MM-dd HH:mm
              let formattedTime = ''
              if (item.reservationTime) {
                const dateTime = new Date(item.reservationTime)
                if (!isNaN(dateTime.getTime())) {
                  const year = dateTime.getFullYear()
                  const month = (dateTime.getMonth() + 1).toString().padStart(2, '0')
                  const day = dateTime.getDate().toString().padStart(2, '0')
                  const hours = dateTime.getHours().toString().padStart(2, '0')
                  const minutes = dateTime.getMinutes().toString().padStart(2, '0')
                  formattedTime = `${year}-${month}-${day} ${hours}:${minutes}`
                } else {
                  formattedTime = item.reservationTime
                }
              }

              return {
                id: item.id,
                appointmentTime: formattedTime,
                orderNo: item.orderNo || '',
                tag: item.urgent == 1 ? '加急' : '',
                customerName: item.ownerName ? this.maskName(item.ownerName) : '',
                customerAvatar: item.customerAvatar || '/static/images/profile.jpg',
                serviceType: item.measureDescribe || '',
                orderType: item.orderType || '1',
                address: (item.ownerProvincial || '') + (item.ownerCity || '') + (item.ownerCounty || '') + (item.ownerAddress || ''),
                price: item.orderFee || '0.00',
                orderStatus: item.orderStatus || '1'
              }
            })

            this.orderList = [...this.orderList, ...processedOrders]
          } else {
            uni.showToast({
              title: res.msg || '获取加急订单数据失败',
              icon: 'none'
            })
            if (this.pageNum === 1) {
              this.noData = true
              this.orderList = []
            }
          }
        })
        .catch((err) => {
          console.error('获取加急订单数据失败:', err)
          uni.showToast({
            title: '获取加急订单数据失败，请稍后重试',
            icon: 'none'
          })
          if (this.pageNum === 1) {
            this.noData = true
            this.orderList = []
          }
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.urgent-order-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #0088ff;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon-img {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
}

/* 订单列表 */
.order-list {
  height: calc(100vh - 90rpx);
  padding: 20rpx;
  background-color: #f5f5f5;
}

.order-item {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx;
  position: relative;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 预约时间 */
.appointment-time {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.time-value {
  color: #ff8c00;
  font-size: 32rpx;
  font-weight: bold;
}

/* 订单编号和标签 */
.order-header {
  margin-bottom: 20rpx;
}

.order-no-container {
  display: flex;
  align-items: center;
}

.order-no {
  font-size: 28rpx;
  color: #333;
}

.order-tag {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  margin-left: 10rpx;
  color: #fff;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.tag-icon {
  display: inline-block;
  width: 20rpx;
  height: 20rpx;
  line-height: 20rpx;
  text-align: center;
  border-radius: 50%;
  background-color: #fff;
  color: #ff3b30;
  font-weight: bold;
  margin-right: 4rpx;
  font-size: 20rpx;
}

.urgent-tag {
  background-color: #ff3b30;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 客户信息和服务类型 */
.customer-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.customer-left {
  display: flex;
  align-items: center;
}

.location-icon {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10rpx;
}

.icon-img {
  width: 40rpx;
  height: 40rpx;
}

.customer-details {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.customer-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 15rpx;
}

.service-type-tag {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 30rpx;
  color: #fff;
  display: inline-block;
  line-height: 1.5;
}

.measure-tag {
  background-color: #4cd964;
}

.install-tag {
  background-color: #007aff;
}

.service-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  color: #ff3b30;
}

.price {
  font-size: 36rpx;
  font-weight: bold;
  margin-top: 5rpx;
}

/* 地址 */
.order-address {
  margin-bottom: 20rpx;
  padding-left: 60rpx;
}

.address-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.4;
}

/* 查看详情按钮 */
.order-footer {
  display: flex;
  justify-content: flex-end;
}

.detail-btn {
  background-color: #fff;
  color: #0088ff;
  font-size: 28rpx;
  padding: 8rpx 30rpx;
  border-radius: 30rpx;
  border: 1px solid #0088ff;
  line-height: 1.5;
  margin: 0 10rpx 0 0;
}

/* 无数据提示 */
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}
</style>